module.exports = function($scope, $resource, $state, $stateParams, $http, $q, 
    date2str, FileUploader, model, category){

    //商品模版id
	var id = $stateParams.id;
    //商品id
    var goodsid = $stateParams.goodsid;
    console.log(goodsid);
    //商品编号
    var goodscode = '';
    $scope.goodscode = '';
    //商品渠道对象
    var goodsChannelObj = {};
    $scope.selectobj = {};


    $scope.dateshow = {};
    $scope.timeshow = {};
    $scope.imageshow = {};
    $scope.result = {};

    $scope.step = [];

    $scope.channelitem = {};
    $scope.channelresult = {};
    $scope.channeldateshow = {};
    $scope.channeltimeshow = {};
    $scope.channelimageshow = {};

    
    $scope.category = category;



    // ------- 有效时间 -----------------//
    $scope.hstep = 1;
    $scope.mstep = 15;

    $scope.ismeridian = true;

    $scope.changed = function () {
    //$log.log('Time changed to: ' + $scope.mytime);
    };
    // ------- 有效时间 -----------------//

    $scope.steps = {
        'percent' : 5,
        'step1' : true,
        'step2' : false,
        'step3' : false,
    };

    var beforedata = {
        //商品模板信息
        'goodsTempInfo' : 
        $http({
            'method' : 'GET', 
            'url': '/api/ac/tc/goodsTemplete/info',
            'params' : {'id' : id}
        }),
        //渠道列表
        'channelTempList' :
        $http({
            'method' : 'GET', 
            'url': '/api/ac/tc/channelTemplete/jlist'
        }),
        //短信信息
        'smsinfo' :
        $http({
            'method' : 'GET', 
            'url': '/api/as/tc/salesmstemplate/list',
        }),
        
    };


    if(goodsid != ''){
        beforedata['goodsinfo'] = $http({
            'method' : 'GET', 
            'url': '/api/ac/tc/ticketGoods/getTicketGoodsInfo',
            'params' : {
                'id' : goodsid
            }
        });
    }


    $q.all(beforedata).then(function(res){

        if(res.goodsTempInfo.data.errcode === 0){
            console.log(res.goodsTempInfo.data);
        }else{
            alert('/api/ac/tc/goodsTemplete/info' + res.goodsTempInfo.data.errmsg);
            return ;
        }

        if(res.channelTempList.data.errcode === 0){
            console.log(res.channelTempList.data);
        }else{
            alert('/api/ac/tc/channelTemplete/jlist' + res.channelTempList.data.errmsg);
            return ;
        }

        if(angular.isDefined(res.goodsinfo)){
            if(res.goodsinfo.data.errcode === 0){
                console.log(res.goodsinfo.data);
            }else{
                //alert('/api/ac/tc/ticketGoods/getTicketGoodsInfo' + res.goodsinfo.data.errmsg);
                //return ;
            }
        }

        if(res.smsinfo.data.errcode === 0){
            console.log(res.smsinfo.data);
        }else{
            alert('/api/as/tc/salesmstemplate/list' + res.smsinfo.data.errmsg);
            return ;
        }

        //----------- 短信下拉 --------------------------//
        $scope.selectobj['smsinfo'] = {
            'data' : res.smsinfo.data.data,
            'txt' : '',
            'change' : function(id){
                for(var i = 0; i < this.data.length; i++){
                    var tmp = this.data[i];
                    if(tmp.sms_template_id == id){
                        this.txt = tmp.sms_diy;
                    }
                }
            }
        };
        //----------- 短信下拉 --------------------------//
        
        //不需要用户添的信息
        var lockobj = angular.fromJson(res.goodsTempInfo.data.data.templete_lock_data_json);
        angular.forEach(lockobj, function(value, key){
            $scope.result[key] = value;
        });

        console.log('锁定的对象');
        console.log(lockobj);

        //需要用户填的信息
        var unlock = res.goodsTempInfo.data.data.templete_check_data_json;
        var unlockarr = unlock.split('#');
        var unlockobj = {};
        for(var i = 1; i < unlockarr.length - 1; i++)
        {
            var tmp = unlockarr[i];

            if(angular.isUndefined(model[tmp])){
                console.log('属性不存在' + tmp);
                continue;
            }
            if(angular.isDefined(model[tmp].value)){
                $scope.result[tmp] = unlockobj[tmp] = model[tmp].value;
            }else{
                $scope.result[tmp] = unlockobj[tmp] = '';
            }
        }

        console.log('未锁定的对象');
        console.log(unlockobj);

        if(angular.isDefined(res.goodsinfo)){
            var goodsinfo = res.goodsinfo.data.data;
            angular.forEach(goodsinfo, function(value, key){
                //获取商品编号
                if(key === 'goods_code'){
                    goodscode = value;
                    $scope.goodscode = value;
                }
                //获取商品渠道信息
                if(key === 'channelInfoList'){
                    for(var i = 0; i < value.length; i++){
                        var tt = value[i];
                        goodsChannelObj[tt.templete_code] = tt;
                    }
                }
                if(key === 'ticketTypeList'){
                    $scope.selectobj['ticketTypeList'] = value;
                }
                if(angular.isDefined(model[key])){
                    if(model[key].type == 'number')
                    {
                        $scope.result[key] = parseInt(value);
                    }
                    else if(model[key].type == 'float')
                    {
                        $scope.result[key] = parseFloat(value);
                    }
                    else
                    {
                        $scope.result[key] = value;
                    }
                }
                
                // if(key === 'tpsp.period_model_valid_week'){

                // }else{
                //     $scope.result[key] = value;
                // }
            });
        }

        //生成显示数组
        var showarr = [];//用来显示的arr
        for(var i = 0, j = $scope.category.length; i < j; i++){
            var tmp1 = $scope.category[i];
            var showobj = {
                'remark' : tmp1.name,
                'data' : [],
                'active': tmp1.active
            };

            for(var m = 0, n = tmp1.data.length; m < n; m++){
                var tmp2 = tmp1.data[m];
                //lockobj,unlockobj中不存在这个属性
                if(angular.isUndefined(unlockobj[tmp2]) 
                && angular.isUndefined(lockobj[tmp2]) ){
                    continue;
                }

                if(angular.isDefined(lockobj[tmp2])){
                    model[tmp2]['lock'] = true;
                    model[tmp2]['value'] = lockobj[tmp2];
                }

                //console.log(tmp2);

                if(model[tmp2].type === 'date1')
                {
                    var dddd = '';

                    if(angular.isDefined(goodsinfo)){
                        dddd = goodsinfo[tmp2];
                    } else {
                        dddd = date2str(new Date());
                    }

                    $scope.dateshow[tmp2] = {
                        'label' : dddd,
                        'opened' : false,
                    };
                }

                if(model[tmp2].type === 'time')
                {

                    var strh = '';
                    if(angular.isDefined(goodsinfo)){
                        strh = goodsinfo[tmp2];
                    } else {
                        strh = model[tmp2].value;
                    }

                    var hh = strh.split(':')[0];
                    var mm = strh.split(':')[1];

                    var d = new Date();
                    d.setHours(hh);
                    d.setMinutes(mm);
                    // $scope.result['tpsp.day_usetime_period_start'] = d1;

                    $scope.timeshow[tmp2] = {
                        'label' : d,
                    };
                }

                if(model[tmp2].type === 'image')
                {
                    (function(tmp){

                        var uploader = new FileUploader({
                            url: 'http://cl.juyouhx.com/oss.php/oss/webuploader1?topdir=aa&selfdir=bb'
                        });

                        $scope.imageshow[tmp] = {
                            'uploader' : uploader
                        };

                        uploader.filters.push({
                            name: 'imageFilter',
                            fn: function(item, options) {
                                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                            }
                        }); 

                        uploader.onSuccessItem = function(fileItem, response, status, headers) {
                            //console.log(response.savename);
                            //console.log(tmp);
                            $scope.result[tmp] = response.savename;
                        };

                    })(tmp2);
                }

                showobj.data.push(model[tmp2]);

            }
            showarr.push(showobj);
        }

        $scope.model = model;

        showarr.push({
            'remark' : '设置渠道',
            'data' : [],
            'active': false,
        });

        $scope.arr = showarr;
        console.log($scope.arr);
        console.log('ok');


                    
        console.log(goodsChannelObj);

        //---------- 设置渠道 -----------------------//
        var channelarr = res.channelTempList.data.data;
        console.log(channelarr);

        for(var i = 0; i < channelarr.length; i++){
            var t = channelarr[i];
            var tmp = t.templete_check_data_json;
            var tmparr = tmp.split('#');
            t['obj'] = {};
            t['dateshow'] = {};
            t['timeshow'] = {};
            t['imageshow'] = {};
            t['result'] = {};
            t['data'] = [];
            t['haschannel'] = false;

            for(var m = 1; m < tmparr.length - 1; m++){
                var tmp1 = tmparr[m];

                if(angular.isUndefined(model[tmp1])){
                    continue;
                }

                if(angular.isDefined(model[tmp1].value)){
                    t.result[tmp1] = t['obj'][tmp1] = model[tmp1].value;
                }else{
                    t.result[tmp1] = t['obj'][tmp1] = '';
                }

            }

            for(var m = 0; m < $scope.category.length; m++){
                var tmp1 = $scope.category[m];
                for(var n = 0; n < tmp1.data.length; n++){
                    var tmp2 = tmp1.data[n];
                    if(angular.isUndefined(t['obj'][tmp2])){
                        continue;
                    }

                    if(model[tmp2].type === 'date1')
                    {
                        t.dateshow[tmp2] = {
                            'label' : date2str(new Date()),
                            'opened' : false,
                        };
                    }

                    if(model[tmp2].type === 'time')
                    {
                        var strh = model[tmp2].value;

                        var hh = strh.split(':')[0];
                        var mm = strh.split(':')[1];

                        var d = new Date();
                        d.setHours(hh);
                        d.setMinutes(mm);
                        // $scope.result['tpsp.day_usetime_period_start'] = d1;

                        t.timeshow[tmp2] = {
                            'label' : d,
                        };
                    }

                    if(model[tmp2].type === 'image')
                    {
                        (function(tmp){

                            var uploader = new FileUploader({
                                url: 'http://cl.juyouhx.com/oss.php/oss/webuploader1?topdir=aa&selfdir=bb'
                            });

                            t.imageshow[tmp] = {
                                'uploader' : uploader
                            };

                            uploader.filters.push({
                                name: 'imageFilter',
                                fn: function(item, options) {
                                    var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                    return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                                }
                            }); 

                            uploader.onSuccessItem = function(fileItem, response, status, headers) {
                                console.log(t);
                                t.result[tmp] = response.savename;
                            };

                        })(tmp2);
                    }

                    t.data.push(model[tmp2]);

                }
            }

            //如果该商品有这个渠道的信息
            if(angular.isDefined(goodsChannelObj[t.templete_code])){
                t['haschannel'] = true;
                var gc = goodsChannelObj[t.templete_code];
                console.log(goodsChannelObj[t.templete_code]);
                console.log(t);
                for(var k = 0; k < t.data.length; k++){
                    var kk = t.data[k];

                    if(angular.isDefined(gc[kk.id])){
                        if(kk.type == 'number')
                        {
                            t.result[kk.id] = parseInt(gc[kk.id]);
                        }
                        else
                        {
                            t.result[kk.id] = gc[kk.id];
                        }
                    }
                }
            }

        }

        $scope.channelarr = channelarr;
    });


    $scope.create = function(item){
    	$state.go('app.goods_info_create', {'id' : item.id});
    }

    //打开日历控件
    $scope.open = function($event, item){
        $event.preventDefault();
        $event.stopPropagation();
        item.opened = true;
    };

    //保存
    $scope.gogogo = function(){
        savegoods('channel');
    }

    //保存并返回列表
    $scope.gogogolist = function(){
        savegoods('list');
    };

    function savegoods(what){

        //获取到表单是否验证通过
        for(var i = 0; i < $scope.step.length; i++){
            if($scope.step[i].$valid){
                //alert('通过验证可以提交表单');
            }else{
                //alert('表单没有通过验证');
                return ;
            }
        }

        if(angular.isDefined($scope.result['tpsp.period_model_valid_week'])){
            $scope.result['tpsp.period_model_valid_week'] = '1,2';
        }

        //将所有时间对象处理成返回的字符串
        angular.forEach($scope.dateshow, function(value, key){
            if(angular.isDate(value.label)){
                $scope.result[key] = date2str(value.label);
            }else{
                $scope.result[key] = value.label;
            }
        });


        if(angular.isDefined($scope.result['tpst[x].ticket_type_id'])){
            $scope.result['ticket_type_id_arr'] = $scope.result['tpst[x].ticket_type_id'];
            if(angular.isDefined($scope.selectobj['ticketTypeList'])
            && angular.isArray($scope.selectobj['ticketTypeList'])){
                for(var i = 0; i < $scope.selectobj['ticketTypeList'].length; i++){
                    $scope.result['tpst['+i+'].ticket_type_id'] = $scope.selectobj['ticketTypeList'][i].id;
                }
            }
        }
        


        console.log($scope.result);

        $scope.result['goods_templete_id'] = id;

        var url = '';

        if(goodsid != ''){   //修改商品
            url = '/api/ac/tc/ticketGoods/updateTicketGoods';
            $scope.result['id'] = goodsid;
        }else{  //创建商品
            url = '/api/ac/tc/ticketGoods/createTicketGoods';
        }

        console.log(url);

        $resource(url, {}, {}).save($scope.result, function(res){
            console.log(res);
            if(res.errcode === 0){
                if(what === 'list'){
                    $state.go('app.goods_list');
                }
                else if(what === 'channel'){
                    $state.go('app.goods_info_create', 
                        {'id' : id, 'goodsid' : res.data.id});
                }else{
                    return;
                }
            }else{
                alert(res.errmsg);
            }
        });
    }

    $scope.next = function(arr, index){

        arr[index].active = false;
        arr[index+1].active = true;

    };

    $scope.pre = function(arr, index){
        arr[index].active = false;
        arr[index-1].active = true;
    };

    //选择渠道
    $scope.choicechannel = function(item){
        console.log(item);
        $scope.channelitem = item;
        $scope.channelresult = item.result;
        $scope.channeldateshow = item.dateshow;
        $scope.channeltimeshow = item.timeshow;
        $scope.channelimageshow = item.imageshow;
    };




    $scope.savechannel = function(){

        var channelcode = $scope.channelitem.templete_code;
        console.log(channelcode);
        console.log(goodscode);

        if(angular.isDefined($scope.channelresult['tpsp.period_model_valid_week'])){
            $scope.channelresult['tpsp.period_model_valid_week'] = '1,2';
        }

        //将所有时间对象处理成返回的字符串
        angular.forEach($scope.channeldateshow, function(value, key){
            if(angular.isDate(value.label)){
                $scope.channelresult[key] = date2str(value.label);
            }else{
                $scope.channelresult[key] = value.label;
            }
        });

        var url = '/api/ac/tc/goodsChannelInfo/create';
        $scope.channelresult['goods_id'] = goodscode;
        $scope.channelresult['templete_id'] = channelcode;

        console.log($scope.channelresult);

        $resource(url, {}, {}).save($scope.channelresult, function(res){
            console.log(res);
            if(res.errcode === 0){
                alert(res.data.describe);
                
            }else{
                alert(res.errmsg);
            }
        });

    };

};